const puppeteer = require('puppeteer');
const path = require('path');

(async () => {
  const extensionPath = path.resolve(__dirname, '..');
  console.log('Extension path:', extensionPath);

  const browser = await puppeteer.launch({
    headless: false,
    args: [
      `--disable-extensions-except=${extensionPath}`,
      `--load-extension=${extensionPath}`,
      '--no-sandbox',
      '--disable-setuid-sandbox'
    ],
    defaultViewport: null
  });

  try {
    // generic sleep helper
    const sleep = ms => new Promise(r => setTimeout(r, ms));

    // wait a short while for extension to load
    await sleep(1500);

    const targets = await browser.targets();
    // find a target whose url starts with chrome-extension:// and extract id
    let extId = null;
    for (const t of targets) {
      const u = t.url && t.url();
      if (u && u.startsWith('chrome-extension://')) {
        const m = u.match(/^chrome-extension:\/\/([a-p]{32})\//i);
        if (m) {
          extId = m[1];
          break;
        }
        // fallback: try to parse id between slashes
        const parts = u.split('/');
        if (parts.length >= 3) {
          extId = parts[2];
          break;
        }
      }
    }

    console.log('Detected extension id (may be null):', extId);

    if (extId) {
      const popupUrl = `chrome-extension://${extId}/popup.html`;
      const popup = await browser.newPage();
      popup.on('console', msg => console.log('[popup]', msg.text()));
      popup.on('pageerror', err => console.error('[popup][pageerror]', err));
      console.log('Opening popup URL:', popupUrl);
      await popup.goto(popupUrl).catch(e => console.error('Open popup error', e));

      // Wait a bit to capture console logs
      await sleep(3000);
      await popup.screenshot({ path: 'popup.png' });
      console.log('Popup screenshot saved to popup.png');
    } else {
      console.log('Could not automatically determine extension id. Please open the popup manually in the browser and check console.');
    }

    console.log('Done. Close browser manually to end.');
  } catch (err) {
    console.error('Test script error:', err);
    await browser.close();
    process.exit(1);
  }
})();
